Download 320*480px JPEG Image collection For Testing

Bonrix Dynamic QR Code Scanner Display (DQR-111) Image (JPEG) Display Model


Javascript Code:

Java Example:


    package com.image;
    import com.fazecast.jSerialComm.*;

    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.concurrent.TimeUnit;
    import java.io.InputStream;

    public class testing {
        private static SerialPort serialPort;

        public static void main(String[] args) {
            try {
                String filePath = "src/main/resources/static/new.jpeg"; // replace with your JPEG file path. Image must be 320x480 size
                String comPort = "COM5"; // set COM port like COM3
                int baudRate = 156500; // set baud rate
                int chunkSize = 1024;
                int delayBetweenChunk = 10; // in milliseconds

                // Open and configure the serial port
                serialPort = SerialPort.getCommPort(comPort);
                serialPort.setBaudRate(baudRate);
                serialPort.setNumDataBits(8);
                serialPort.setNumStopBits(SerialPort.ONE_STOP_BIT);
                serialPort.setParity(SerialPort.NO_PARITY);
                serialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
                serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 0, 0);

                if (!serialPort.openPort()) {
                    System.out.println("Failed to open port " + comPort);
                    return;
                }

                // Wait for the port to stabilize
                TimeUnit.SECONDS.sleep(2);

                byte[] imageBytes = Files.readAllBytes(Paths.get(filePath));

                // Clear existing read buffer
                serialPort.readBytes(new byte[serialPort.bytesAvailable()], serialPort.bytesAvailable());

                String writeString = "StartSendingFile " + System.currentTimeMillis() + ".jpeg " + imageBytes.length + "\n";
                serialPort.writeBytes(writeString.getBytes(), writeString.length());

                System.out.println("String ::::"+writeString);
                //String response = "";
              // int retryGetResponse = 0;
              // byte[] buffer = new byte[1024];

          /*
          * while (true) { if (retryGetResponse < 50) { int len =
          * serialPort.readBytes(buffer, buffer.length); response = new String(buffer, 0,
          * len).trim(); if (response.isEmpty()) {
          * System.out.println("Response: no response from serial"); } else {
          * System.out.println("Response: " + response); if (isSendCommand(response)) {
          * break; } } TimeUnit.MILLISECONDS.sleep(100); retryGetResponse++; } else {
          * break; } }
          */
                String line = null;
                try {
                    line = readLineFromSerial(serialPort.getInputStream());
                    System.out.println("Read line: " + line);
                } catch (IOException e) {
                    e.printStackTrace();
                } 
                
              // TimeUnit.MILLISECONDS.sleep(3000);
                if (line.startsWith("Command received")) {
                    for (int i = 0; i < imageBytes.length; i += chunkSize) {
                        int remainingBytes = Math.min(chunkSize, imageBytes.length - i);
                        serialPort.writeBytes(imageBytes, remainingBytes, i);
                        if (delayBetweenChunk > 0) {
                            TimeUnit.MILLISECONDS.sleep(delayBetweenChunk);
                        }
                    }
                }
                System.out.println("Send Successfully");
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            } 
            try {
                String line = readLineFromSerial(serialPort.getInputStream());
                System.out.println("Read line: " + line);
            } catch (IOException e) {
                e.printStackTrace();
            } 
            /*finally {
                if (serialPort != null && serialPort.isOpen()) {
                    serialPort.closePort();
                }
            }*/
        }
        
        public static String readLineFromSerial(InputStream inputStream) throws IOException {
            StringBuilder line = new StringBuilder();
            int nextByte;
            while ((nextByte = inputStream.read()) != -1) {
                if (nextByte == '\n') {
                    break;
                }
                line.append((char) nextByte);
            }
            return line.toString();
        }

      /* private static boolean isSendCommand(String response) {
            return response.equalsIgnoreCase("ready to receive data chunks...") ||
                  response.equalsIgnoreCase("ready to receive data chunks") ||
                  response.equalsIgnoreCase("command received. preparing to receive file...") ||
                  response.equalsIgnoreCase("command received. preparing to receive file");
        }*/
    }


  

C#.NET Example:


    using System;
    using System.Collections.Generic;
    using System.IO.Ports;
    using System.Linq;
    using System.Text;
    using System.Threading;

    namespace ConsoleApp1
    {
        internal class Program
        {
            static SerialPort serialPort;
            static void Main(string[] args)
            {
                try
                {
                    string filePath = "E:\\desktopapp4\\drive\\dq111welcome.jpg"; //replace your jpeg file path.here your image must be 320X480 size
                    string comPort = "COM8"; //set com port like COM3
                    int baudrate = 156500; //set baudrate
                    int chunkSize = 100;
                    int delayBetweenChunk = 10;
                    // Define the serial port
                    serialPort = new SerialPort(comPort, baudrate, Parity.None, 8, StopBits.One);
                    serialPort.ReadTimeout = 30 * 1000;
                    // Open the serial port
                    serialPort.Open();

                    byte[] imageBytes = System.IO.File.ReadAllBytes(filePath);
                    Thread.Sleep(2000);
                    //clear existing read buffer
                    serialPort.ReadExisting();
                    string writeString = "StartSendingFile " + DateTime.Now.Ticks.ToString() + ".jpeg" + " " + imageBytes.Length.ToString() + "\n";
                    serialPort.Write(writeString);
                    string response = "";
                    int retryGetResponse = 0;
                    while (true)
                    {
                        if (retryGetResponse < 50)
                        {
                            try
                            {
                                response = serialPort.ReadLine();
                                if (string.IsNullOrWhiteSpace(response))
                                {
                                    Console.WriteLine("Response :- " + "no response from serial");
                                }
                                else
                                {
                                    Console.WriteLine("Response :- " + response);
                                    if (IsSendCommand(response))
                                    {
                                        break;
                                    }
                                }
                            }
                            catch
                            {

                            }
                            Thread.Sleep(100);
                            retryGetResponse++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (IsSendCommand(response))
                    {
                        for (int i = 0; i < imageBytes.Length; i += chunkSize)
                        {
                            int remainingBytes = Math.Min(chunkSize, imageBytes.Length - i);
                            serialPort.Write(imageBytes, i, remainingBytes);
                            if (delayBetweenChunk > 0)
                            {
                                Thread.Sleep(delayBetweenChunk);
                            }
                        }
                    }
                    Console.WriteLine("Send Successfully");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    if (serialPort != null)
                    {
                        if (serialPort.IsOpen)
                        {
                            serialPort.Close();
                        }
                    }
                }
                Console.ReadKey();
            }
            public static bool IsSendCommand(string response)
            {
                if (response.ToLower().ToString().Trim() == "ready to receive data chunks...".ToLower().ToString().Trim() || response.ToLower().ToString().Trim() == "ready to receive data chunks".ToLower().ToString().Trim() || response.ToLower().ToString().Trim() == "command received. preparing to receive file...".ToLower().ToString().Trim() || response.ToLower().ToString().Trim() == "command received. preparing to receive file".ToLower().ToString().Trim())
                {
                    return true;
                }
                return false;
            }
        }
    }
  

Python Example:


    import time
    import serial

    def is_send_command(response):
        return response.lower().strip() in ["ready to receive data chunks...",
                                            "ready to receive data chunks",
                                            "command received. preparing to receive file...",
                                            "command received. preparing to receive file"]

    def main():
        try:
            file_path = "C:\\Users\\Dell\\Downloads\\w.jpeg"  # replace your jpeg file path. here your image must be 320X480 size
            com_port = "COM66"  # set com port like COM3
            baudrate = 156500  # set baudrate
            chunk_size = 100
            delay_between_chunk = 10
            
            # Define the serial port
            serial_port = serial.Serial(com_port, baudrate, timeout=30)
            
            with open(file_path, 'rb') as image_file:
                image_bytes = image_file.read()

            time.sleep(2)
            # clear existing read buffer
            serial_port.reset_input_buffer()
            write_string = f"StartSendingFile {str(int(time.time() * 1000))}.jpeg {len(image_bytes)}\n"
            serial_port.write(write_string.encode())        
            response = ""
            retry_get_response = 0
            while True:
                if retry_get_response < 50:
                    try:
                        response = serial_port.readline().decode().strip()
                        if not response:
                            print("Response :- no response from serial")
                        else:
                            print(f"Response :- {response}")
                            if is_send_command(response):
                                break
                    except:
                        pass
                    time.sleep(0.1)
                    retry_get_response += 1
                else:
                    break        
            if is_send_command(response):
                for i in range(0, len(image_bytes), chunk_size):
                    remaining_bytes = min(chunk_size, len(image_bytes) - i)
                    serial_port.write(image_bytes[i:i+remaining_bytes])
                    if delay_between_chunk > 0:
                        time.sleep(delay_between_chunk / 1000.0)        
            print("Send Successfully")
        except Exception as ex:
            print(ex)
        finally:
            if serial_port.is_open:
                serial_port.close()
    if _name_ == "_main_":
        main()
  

node.js Example:


    const fs = require('fs');
    const { SerialPort } = require('serialport');
    const path = require('path');

    const isSendCommand = (response) => {
      return ["ready to receive data chunks...",
              "ready to receive data chunks",
              "command received. preparing to receive file...",
              "command received. preparing to receive file"].includes(response.toLowerCase().trim());
    }

    const main = async () => {
      try {
        const filePath = "C:\\Users\\tanma\\Desktop\\image.jpeg"; // replace your jpeg file path. here your image must be 320X480 size
        const comPort = "COM16"; // set COM port like COM3
        const baudRate = 156500; // set baudrate
        const chunkSize = 100;
        const delayBetweenChunk = 10; // in milliseconds

        const port = new SerialPort({
          path: comPort,
          baudRate: baudRate,
          parity: 'none',
          dataBits: 8,
          stopBits: 1,
          timeout: 30000
        });

        port.on('open', async () => {
          console.log('Serial port opened');

          fs.readFile(filePath, (err, imageBytes) => {
            if (err) {
              console.error('Error reading file:', err);
              return;
            }

            setTimeout(() => {
              port.flush(() => {
                const writeString = StartSendingFile ${Date.now()}.jpeg ${imageBytes.length}\n;
                port.write(writeString, (err) => {
                  if (err) {
                    console.error('Error writing to serial port:', err);
                    return;
                  }
                  console.log('Initial write successful');
                  getResponseAndSendData(port, imageBytes, chunkSize, delayBetweenChunk);
                });
              });
            }, 2000);
          });
        });

        const getResponseAndSendData = (port, imageBytes, chunkSize, delayBetweenChunk) => {
          let buffer = '';
          let retryGetResponse = 0;

          const readResponse = () => {
            port.on('data', (data) => {
              buffer += data.toString();
              const responses = buffer.split('\n');
              for (let i = 0; i < responses.length - 1; i++) {
                const response = responses[i].trim();
                if (isSendCommand(response)) {
                  sendImageData(port, imageBytes, chunkSize, delayBetweenChunk);
                  port.removeAllListeners('data');
                  return;
                } else {
                  console.log('Received unexpected response:', response);
                }
              }
              buffer = responses[responses.length - 1];

              if (retryGetResponse < 50) {
                retryGetResponse++;
                setTimeout(readResponse, 100);
              } else {
                console.log('Max retries reached, exiting.');
              }
            });

            port.on('error', (err) => {
              console.error('Error reading from serial port:', err);
            });
          };

          readResponse();
        }

        const sendImageData = (port, imageBytes, chunkSize, delayBetweenChunk) => {
          let i = 0;
          const sendChunk = () => {
            if (i < imageBytes.length) {
              const remainingBytes = Math.min(chunkSize, imageBytes.length - i);
              port.write(imageBytes.slice(i, i + remainingBytes), (err) => {
                if (err) {
                  console.error('Error writing data chunk:', err);
                  return;
                }
                i += chunkSize;
                if (delayBetweenChunk > 0) {
                  setTimeout(sendChunk, delayBetweenChunk);
                } else {
                  sendChunk();
                }
              });
            } else {
              console.log('Send Successfully');
            }
          };

          sendChunk();
        }

        port.on('error', (err) => {
          console.error('Serial port error:', err);
        });

      } catch (ex) {
        console.log(ex);
      }
    };

    if (require.main === module) {
      main();
    }

  

VB.NET Example:


    Imports System.IO.Ports
    Imports System.Threading

    Module Module1
        Private serialPort As SerialPort
        Sub Main()
            Try
                Dim filePath As String = "E:\desktopapp4\drive\dq111welcome.jpg" 'replace your jpeg file path. here your image must be 320X480 size
                Dim comPort As String = "COM8" 'set com port like COM3
                Dim baudrate As Integer = 156500 'set baudrate
                Dim chunkSize As Integer = 100
                Dim delayBetweenChunk As Integer = 10
                ' Define the serial port
                serialPort = New SerialPort(comPort, baudrate, Parity.None, 8, StopBits.One)
                serialPort.ReadTimeout = 30 * 1000
                ' Open the serial port
                serialPort.Open()

                Dim imageBytes As Byte() = System.IO.File.ReadAllBytes(filePath)
                Thread.Sleep(2000)
                'clear existing read buffer
                serialPort.ReadExisting()
                Dim writeString As String = "StartSendingFile " & DateTime.Now.Ticks.ToString() & ".jpeg" & " " & imageBytes.Length.ToString() & vbLf
                serialPort.Write(writeString)
                Dim response As String = ""
                Dim retryGetResponse As Integer = 0

                While True
                    If retryGetResponse < 50 Then
                        Try
                            response = serialPort.ReadLine()
                            If String.IsNullOrWhiteSpace(response) Then
                                Console.WriteLine("Response :- " & "no response from serial")
                            Else
                                Console.WriteLine("Response :- " & response)
                                If IsSendCommand(response) Then
                                    Exit While
                                End If
                            End If
                        Catch
                        End Try
                        Thread.Sleep(100)
                        retryGetResponse += 1
                    Else
                        Exit While
                    End If
                End While

                If IsSendCommand(response) Then
                    For i As Integer = 0 To imageBytes.Length - 1 Step chunkSize
                        Dim remainingBytes As Integer = Math.Min(chunkSize, imageBytes.Length - i)
                        serialPort.Write(imageBytes, i, remainingBytes)
                        If delayBetweenChunk > 0 Then
                            Thread.Sleep(delayBetweenChunk)
                        End If
                    Next
                End If

                Console.WriteLine("Send Successfully")
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            Finally
                If serialPort IsNot Nothing Then
                    If serialPort.IsOpen Then
                        serialPort.Close()
                    End If
                End If
            End Try
            Console.ReadKey()
        End Sub
        Public Function IsSendCommand(response As String) As Boolean
            If response.ToLower().Trim() = "ready to receive data chunks...".ToLower().Trim() OrElse response.ToLower().Trim() = "ready to receive data chunks".ToLower().Trim() OrElse response.ToLower().Trim() = "command received. preparing to receive file...".ToLower().Trim() OrElse response.ToLower().Trim() = "command received. preparing to receive file".ToLower().Trim() Then
                Return True
            End If
            Return False
        End Function
    End Module